﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using InnovTech.Util.Crypto;
using InnovTech.Util.Text;
using InnovTech.Util.Xml;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace InnovTech.Util.Test
{
    [TestClass]
    public class TestSerializableCryptoAlgo
    {
        [TestMethod]
        public void TestCryptoAlgo()
        {
            string utf8String = Utf8Util.CreateCharSets();

            Guid seed = Guid.NewGuid();
            SymmetricAlgorithm provider = CryptoUtil.CreateCryptoProvider<TripleDESCryptoServiceProvider>(
                CryptoUtil.GenerateBytes(seed, new byte[] { 23 }, 24), CryptoUtil.GenerateBytes(seed, new byte[] { 23 }, 8));
            string base64 = CryptoUtil.EncryptToBase64String(utf8String, provider);

            SerializableCryptoAlgo sca = SerializableCryptoAlgo.Create(provider);

            CryptoXmlSerializer ser = new CryptoXmlSerializer(provider);
            string fileName = "TestSerializableCryptoAlgo";
            string path = Path.Combine(Directory.GetCurrentDirectory(), fileName);
            using (FileStream fs = File.Create(path))
            {
                ser.Serialize(fs, sca);
                fs.Close();
            }

            SerializableCryptoAlgo algo = null;
            using (FileStream fs = File.OpenRead(path))
            {
                algo = ser.Deserialize(fs, typeof(SerializableCryptoAlgo)) as SerializableCryptoAlgo;
                fs.Close();
            }
            Assert.IsNotNull(algo);

            SymmetricAlgorithm decoder = algo.Restore();

            string decrypted = CryptoUtil.DecryptFromBase64String(base64, decoder);
            Assert.AreEqual(utf8String, decrypted);
        }
    }
}
